<template>
  <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
    <a-row :gutter="gutter">
      <a-col :span="24">
        <a-form-item label="Contacts" name="Contacts">
          <a-input v-model:value="contacts" :disabled="true" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Communication Method" name="CommunicationMethod">
          <a-select
            v-model:value="apiData.CommunicationMethod"
            :get-popup-container="triggerNode => triggerNode.parentNode">
            <a-select-option v-for="item in dict.communicationMethods" :key="item.value">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Communication Time" name="CommunicationTime">
          <a-date-picker
            v-model:value="apiData.CommunicationTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            style="width: 100%" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="12">
        <a-form-item label="Communication Category" name="CommunicationCategory">
          <a-select
            v-model:value="apiData.CommunicationCategory"
            :get-popup-container="triggerNode => triggerNode.parentNode">
            <a-select-option v-for="item in dict.communicationCategories" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Attachment" name="fileName">
          <a-input :value="fileName" :readonly="true">
            <template #addonAfter>
              <input v-show="false" ref="uploadInput" type="file" @change="uploadFileChange" />
              <span style="color: #a9b5c9; cursor: pointer" @click="uploadInput.click()">
                <e-icon type="upload" style="margin-right: 6px" />Upload
              </span>
            </template>
          </a-input>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="24">
        <a-form-item label="Communication Subject" name="CommunicationSubject">
          <a-textarea v-model:value="apiData.CommunicationSubject" :auto-size="{ minRows: 4, maxRows: 4 }" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="gutter">
      <a-col :span="24">
        <a-form-item label="Next Communication" name="NextCommunication">
          <a-input v-model:value="apiData.NextCommunication" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { useStore } from 'vuex'
import EIcon from '@/components/EIcon.vue'
import TargetClient from '@/api/targetClient.js'
import { UPLOAD_FAILED } from '@/constants/message.js'
import dayjs from 'dayjs'
const { message } = inject('Feedback')
const gutter = [120, 16]
const formInstance = ref(null)
const uploadInput = ref(null)
// 由上一步表单提供数据父组件设置，不需要修改，不用传递给接口
const contacts = ref('')
// 暴露设置contacts方法给父组件
const setContacts = val => (contacts.value = val)
const fileName = ref('')
const apiData = reactive({
  CommunicationMethod: '',
  CommunicationCategory: '',
  // 联系时间
  CommunicationTime: null,
  CommunicationSubject: '',
  NextCommunication: '',
  AttachmentAddr: '',
  AttachmentFileSize: '',
  AttachmentName: ''
})
const store = useStore()
const dict = ref(computed(() => store.state.dict))
store.dispatch('dict/getCommunicationMethods').then(() => {
  if (dict.value.communicationMethods.length > 0) apiData.CommunicationMethod = dict.value.communicationMethods[0].value
})
store.dispatch('dict/getCommunicationCategories').then(() => {
  if (dict.value.communicationCategories.length > 0) {
    apiData.CommunicationCategory = dict.value.communicationCategories[0].text
  }
})
const rules = {
  CommunicationMethod: [
    {
      type: 'number',
      required: true,
      message: 'Please select a communication method',
      trigger: 'blur'
    }
  ],
  CommunicationTime: [
    {
      required: true,
      message: 'Please select the communication time',
      trigger: 'blur'
    }
  ],
  CommunicationCategory: [
    {
      required: true,
      message: 'Please select a communication category',
      trigger: 'blur'
    }
  ],
  CommunicationSubject: [
    {
      required: true,
      whitespace: true,
      message: 'Please input communication subject',
      trigger: 'blur'
    }
  ],
  NextCommunication: [
    {
      required: true,
      whitespace: true,
      message: 'Please input next communication',
      trigger: 'blur'
    }
  ],
  fileName: [
    {
      required: true,
      validator: () => {
        return fileName.value ? Promise.resolve() : Promise.reject(new Error())
      },
      message: 'Please upload attachment',
      trigger: 'change'
    }
  ]
}
const disabledDate = current => {
  return current > dayjs().endOf('day')
}
const uploadFileChange = event => {
  if (event.target.files.length > 0) {
    TargetClient.uploadFiles(event.target.files)
      .then(res => {
        if (Array.isArray(res) && res.length > 0 && res[0] instanceof Eci.IO.File) {
          fileName.value = event.target.files.length > 0 ? event.target.files[0].name : ''
          apiData.AttachmentAddr = res[0].Path
          apiData.AttachmentFileSize = res[0].SourceBaseFileSize
          apiData.AttachmentName = fileName.value
          formInstance.value.clearValidate('fileName')
        } else {
          fileName.value = ''
          uploadInput.value.value = null
          message.error(UPLOAD_FAILED)
        }
      })
      .catch(() => {
        fileName.value = ''
        uploadInput.value.value = null
        message.error(UPLOAD_FAILED)
      })
  }
}
defineExpose({ formInstance, apiData, setContacts })
</script>

<style scoped></style>
